package com.jzqf.harmonydemo.utils;

import ohos.app.Context;
import ohos.wifi.IpInfo;
import ohos.wifi.WifiDevice;
import ohos.wifi.WifiLinkedInfo;

import java.util.Optional;

/**
 * 网络工具类
 *
 * @author LiuWeiHao
 * 2021/5/17 15:19
 */
public class NetWorkUtil {

    private static final String TAG = NetWorkUtil.class.getSimpleName();

    public static void wifi(Context context) {
        WifiDevice wifiDevice = WifiDevice.getInstance(context);
        //连接状态
        boolean connected = wifiDevice.isConnected();
        Optional<WifiLinkedInfo> linkedInfo = wifiDevice.getLinkedInfo();
        //wifi的ssid
        String ssid = linkedInfo.get().getSsid();
        //IP和网关
        Optional<IpInfo> ipInfo = wifiDevice.getIpInfo();
        int ipAddress = ipInfo.get().getIpAddress();
        int gateway = ipInfo.get().getGateway();
        LogUtil.d(TAG, "wifi connected=" + connected + ",ssid=" + ssid + ",ip=" + intIP2StringIP(ipAddress));
    }

    public static String getIp(Context context) {
        WifiDevice wifiDevice = WifiDevice.getInstance(context);
        //IP和网关
        Optional<IpInfo> ipInfo = wifiDevice.getIpInfo();
        int ipAddress = ipInfo.get().getIpAddress();
        return intIP2StringIP(ipAddress);
    }

    public static String getSsid(Context context) {
        WifiDevice wifiDevice = WifiDevice.getInstance(context);
        Optional<WifiLinkedInfo> linkedInfo = wifiDevice.getLinkedInfo();
        //wifi的ssid
        return linkedInfo.get().getSsid();
    }

    /**
     * 将得到的int类型的IP转换为String类型
     */
    public static String intIP2StringIP(int ip) {
        return (ip & 0xFF) + "." +
                ((ip >> 8) & 0xFF) + "." +
                ((ip >> 16) & 0xFF) + "." +
                (ip >> 24 & 0xFF);
    }
}
